<?php

class Helper
{
	private function __construct(){}
	
	static public function isAjax()
	{
		if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			return true;
		}
		return false;
	}
	
	static public function startSession()
	{
		if(!isset($_SESSION)){
			session_start();
		}
	}
	
	static public function emptys(){
		if(func_num_args() == 1){
			$args = func_get_args();
			return empty($args[0]);
		}
		else if(func_num_args() > 1){
			$args = func_get_args();
			foreach($args as $key => $value){
				if(empty($value)){
					return true;
				}
				return false;
			}
		}
	}
	
	static public function refresh($sec = 1)
	{
		$page = $_SERVER['PHP_SELF'];
		if(count($_GET) > 0){
			$page .= '?'.http_build_query($_GET);
		}
		echo <<<HTML
		<META HTTP-EQUIV=Refresh CONTENT="{$sec}; {$page}" />
HTML;
	}
	
	static public function redir($page, $sec = 1)
	{
		if(gettype($page) == 'string'){
			$url = 'old.php?'.http_build_query(array('page'=> $page));
		}
		else if(gettype($page) == 'array'){
			$url = 'old.php?'.http_build_query($page);
		}
		echo <<<HTML
		<META HTTP-EQUIV=Refresh CONTENT="{$sec}; {$url}" />
HTML;
	}
	
	static public function redirUrl($url, $sec = 1)
	{
		echo <<<HTML
		<META HTTP-EQUIV=Refresh CONTENT="{$sec}; {$url}" />
HTML;
	}
	
	static public function formatMoney($number, $fractional=false) {
		if ($fractional) {
			$number = sprintf('%.2f', $number);
		}
		while (true) {
			$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
			if ($replaced != $number) {
				$number = $replaced;
			} else {
				break;
			}
		}
		return $number;
	}

    static public function strTemplate($str, array $params = array())
    {
        $search = array();
        $replace = array();
        foreach($params as $key => $value){
            $search[$key] = '{{'.$key.'}}';
            $replace[$key] = $value;
        }
        return str_replace($search, $replace, $str);
    }

    static public function listArrVal($keyName, $items)
    {
        $fields = array();
        foreach($items as $key => $item)
            $fields[] = $item[$keyName];
        return $fields;
    }

    static public function findArr($keyName, $keyValue, array $array)
    {
        $buffer = array();
        foreach($array as $key => $item)
            if($item[$keyName]==$keyValue)
                $buffer[] = $item;
        return $buffer;
    }

    static public function findArrOne($keyName, $keyValue, array $array)
    {
        foreach($array as $key => $item)
            if($item[$keyName]==$keyValue)
                return $item;
        return null;
    }

    static public function isAssoc(array $arr)
    {
        return array_keys($arr) !== range(0, count($arr) - 1);
    }

    static public function isNumericArray(array $array) {
        foreach ($array as $a=>$b) {
            if (!is_int($a)) {
                return false;
            }
        }
        return true;
    }
}